package network2;

import java.io.IOException;
import java.net.*;
import java.util.Scanner;

public class UdpEchoClient {

    private DatagramSocket socket = null;
    private String serverIP;
    private int serverPort;

    public UdpEchoClient(String serverIP,int serverPort) throws SocketException {
        socket = new DatagramSocket();
        this.serverIP = serverIP;
        this.serverPort = serverPort;
    }

    public void start() throws IOException {
        Scanner scanner = new Scanner(System.in);
        while (true){
            // 输入
            System.out.printf("->");
            String request = scanner.next();
            // 发送求请求
            DatagramPacket requestPacket = new DatagramPacket(request.getBytes(),request.getBytes().length, InetAddress.getByName(serverIP),serverPort);
            socket.send(requestPacket);
            // 接收回复
            DatagramPacket respondPacket = new DatagramPacket(new byte[4090],4090);
            socket.receive(respondPacket);
            String respond = new String(respondPacket.getData(),0,respondPacket.getLength());
            System.out.printf("发出：%s，收到：%s\n",request,respond);

        }
    }

    public static void main(String[] args) throws IOException {
        UdpEchoClient udpEchoClient = new UdpEchoClient("127.0.0.1",9091);
        udpEchoClient.start();
    }
}
